package com.gxuwz.attend.web.servlet.instructor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxuwz.attend.context.AppContext;
import com.gxuwz.attend.entity.Instructor;
import com.gxuwz.attend.entity.Leave;
import com.gxuwz.attend.service.instructor.AuditService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.List;

@WebServlet("/audit")
public class AuditServlet extends HttpServlet {

    private AuditService auditService;
     ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void init() throws ServletException {
        super.init();
        auditService = AppContext.getBean(AuditService.class);
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Instructor instructor = (Instructor) session.getAttribute("currentUser");
        List<Leave> leaves = auditService.getLeave(instructor.getInstID());
        System.out.println(instructor.getInstID());
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        String json = objectMapper.writeValueAsString(leaves);
        resp.getWriter().write(json);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String leaveId = req.getParameter("leaveId");
        String status = req.getParameter("status");

        // 调用业务逻辑进行审核操作
        boolean rs = auditService.updateLeave(leaveId, status);

        // 设置响应内容类型为 JSON
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        // 返回审核操作的结果
        if (rs) {
            // 操作成功，返回成功的JSON响应
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().write("{\"success\": true, \"message\": \"操作成功\"}");
        } else {
            // 操作失败，返回失败的JSON响应
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().write("{\"success\": false, \"message\": \"操作失败\"}");
        }
    }

}
